# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def goodNodes(self, root: TreeNode) -> int:
        def dfs(node, m, res):
            if node is None:
                return
            if node.val >= m:
                res[0] += 1
            m = max(node.val, m)
            dfs(node.left, m, res)
            dfs(node.right, m, res)

        if root is None:
            return 0

        res = [0]
        dfs(root, root.val, res)
        return res[0]
